package com.foreknow.service.impl;

import com.foreknow.bean.User;
import com.foreknow.dao.UserDao;
import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.UserService;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 业务层(需要处理事物)
 */
public class UserServiceImpl implements UserService {

    @Override
    public boolean addUser(User user) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        boolean isRight = false;
        try {
            isRight = userDao.save(user);
            //提交事物
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //回滚事物
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return isRight; //调用UserDao中的方法
    }

    @Override
    public User isValidate(String adminName, String password) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        User user = null;
        try {
            user = userDao.login(adminName,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
